package cn.chengpengper.seckill.order.application.event.handler;

import cn.chengpengper.seckill.common.constants.SeckillConstants;
import cn.chengpengper.seckill.order.domain.event.SeckillOrderEvent;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

/**
 * @author chengpeng.hu
 */
@Slf4j
@Component
@ConditionalOnProperty(name = "message.mq.type", havingValue = "rocketmq")
@RocketMQMessageListener(consumerGroup = SeckillConstants.EVENT_ORDER_CONSUMER_GROUP, topic = SeckillConstants.TOPIC_EVENT_ROCKETMQ_ORDER)
public class SeckillOrderRocketMqEventHandler implements RocketMQListener<String> {
    @Override
    public void onMessage(String msg) {
        if (StrUtil.isEmpty(msg)){
            log.info("SeckillOrderRocketMqEventHandler|orderEvent|接收订单事件为空");
            return;
        }
        SeckillOrderEvent seckillOrderEvent = this.getEventMessage(msg);
        if (seckillOrderEvent.getId() == null){
            log.info("SeckillOrderRocketMqEventHandler|orderEvent|订单参数错误");
        }
        log.info("SeckillOrderRocketMqEventHandler|orderEvent|接收订单事件|{}", JSON.toJSON(seckillOrderEvent));
    }

    private SeckillOrderEvent getEventMessage(String msg){
        JSONObject jsonObject = JSONObject.parseObject(msg);
        String eventStr = jsonObject.getString(SeckillConstants.MSG_KEY);
        return JSONObject.parseObject(eventStr, SeckillOrderEvent.class);
    }
}
